package com.csdj.server.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author zyq
 * @Date 2023/2/13 11:28
 * @ClassName: CustomAuthorityDeserializer
 * @Description: TODO
 * @Version 1.0
 */
public class CustomAuthorityDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctx) throws IOException, JsonProcessingException {
        //先获取需要解析的数据
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        //读取到 数据节点
        JsonNode treeNode = mapper.readTree(jp);
        //
   /*     "authorities": [
        {
            "authority": "ROLE_admin"
        }
  ],*/
        List<GrantedAuthority> authorityList=new LinkedList<>();
        //遍历节点数据
        Iterator<JsonNode> elements = treeNode.elements();
        while (elements.hasNext()){
            JsonNode next = elements.next();
            JsonNode authorities = next.get("authority");
            authorityList.add(new SimpleGrantedAuthority(authorities.asText()));
        }
        return authorityList;
    }
}
